package com.zzy.transaction.manager;

import com.zzy.transaction.context.TransactionMeta;
import com.zzy.transaction.future.Monitor;
import lombok.SneakyThrows;

public class TransactionCoordinator {

    private static final ThreadLocal<TransactionMeta> TRANSACTION_META_THREAD_LOCAL = new ThreadLocal<>();

    @SneakyThrows
    public static void start(TransactionMeta transactionMeta) {
        transactionMeta.afterPropertiesSet();
        transactionMeta.setMonitor(new Monitor());
        TRANSACTION_META_THREAD_LOCAL.set(transactionMeta);
    }

    public static TransactionMeta get() {
        return TRANSACTION_META_THREAD_LOCAL.get();
    }

    public static void bind(TransactionMeta transactionMeta) {
        TRANSACTION_META_THREAD_LOCAL.set(transactionMeta);
    }

    public static void unbind() {
        TRANSACTION_META_THREAD_LOCAL.remove();
    }

    public static void end() {
        TRANSACTION_META_THREAD_LOCAL.remove();
    }

    public static void normalComplete() {
        Monitor monitor = getMonitor();
        monitor.setError(false,null);
    }

    public static void errorComplete(Throwable cause) {
        Monitor monitor = getMonitor();
        monitor.setError(true, cause);
    }

    public static boolean hasError() {
        Monitor monitor = getMonitor();
        return monitor.isError();
    }

    public static Monitor getMonitor() {
        return get().getMonitor();
    }

}
